package com.workspace.js_website.service;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 媒体文件相关服务
 */

@Service
public class MediaService {
    public void getImage(String imgPath, HttpServletResponse response) throws IOException {
        File file = new File(imgPath);
        if (!file.exists()) {
            response.setStatus(404);
            return;
        }

        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();
        for (int l = inputStream.read(bytes); l != -1; l = inputStream.read(bytes)) {
            out.write(bytes);
        }
        out.flush();
        out.close();
    }

    public void getVideo(String videoPath, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File file = new File(videoPath);
        if (!file.exists()) {
            response.setStatus(404);
            return;
        }

        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        long start = 0;
        long fileLength = file.length();
        FileInputStream ins = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(ins);
        String range = request.getHeader("Range");
        if (range != null && range.trim().length() > 0 && !range.equals("null")) {
            String rangBytes = range.replaceAll("bytes=", "");
            start = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
            bis.skip(start);
        }
        long end = Math.min(start + 1000000, fileLength);
        String contentLength = Long.toString(end - start);
        String contentRange = "bytes " + start + "-" + (end - 1) + "/" + fileLength;
        response.reset();
        response.setStatus(206);
        response.setContentType("video/mp4");
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Range", contentRange);
        response.setHeader("Content-Length", contentLength);
        OutputStream out = response.getOutputStream();
        for (int l = bis.read(bytes); l != -1; l = bis.read(bytes)) {
            out.write(bytes);
        }
        out.flush();
        out.close();
    }
}
